package cn.yusei.teamTribe.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.service.user.TokenService;
import cn.yusei.teamTribe.util.ResponseUtil;

@Controller
public class TokenAuthInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private TokenService tokenService;
	
	@Value("${tokenName}")
	private String tokenName;
	
	private static String[] needNotLogonUrl = 
		{
				"/error", "/hello",
				"/user/login", "/user/register", "/user/authMail/auth/", "/user/authPhone/get",
				"/search/byPhone","/search/byName","/search/byEmail","/search/byTeam","/search/byTag",
				"/sign/getSentence",
				"/team/get",
				"/teamInfo/get",
				"/teamRole/get",
				"/schoolRole/get",
				"/post/getById", "/post/getByUser", "/post/getByTargetId", "/post/getByTeam",
				"/postTag/get",
				"/post/getUser",  "/post/getTeam",
				"/teamPhoto/get",
				"/teamVideo/get",
				"/file/download",
				"/teamMember/getById", "/teamMember/get",
				"/teamAlbum/getById", "/teamAlbum/getByTeam"
		}; 
	
	private static String[] canNotLogonUrl =
		{
				"/userInfo/getById"
		};
	
	private boolean inUrls(String requestUrl, String[] urls)
	{
		for(String url : urls)
		{
			if(requestUrl.startsWith(url))
				return true;
		}
		return false;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String requestUrl = request.getRequestURI();
		//是不需要登录的 url ，直接通过
		if(inUrls(requestUrl, needNotLogonUrl)) {
			return true;
		}
		String teamTribeToken = request.getParameter(tokenName);
		boolean canNotLogon = inUrls(requestUrl, canNotLogonUrl);
		if(teamTribeToken == null) {
			if(canNotLogon) {
				return true;
			}
			ResponseUtil.responseCode(response, ResponseCode.NOT_LOGON);
			return false;
		}
		Integer id = tokenService.getId(teamTribeToken);
		if(id == null) {
			if(canNotLogon) {
				return true;
			}
			ResponseUtil.responseCode(response, ResponseCode.NOT_LOGON);
			return false;
		}
		request.setAttribute("id", id);
		return true;
	}
	
}
